"""
Request logging middleware
"""
import time
import logging
import json
from typing import Dict, Any
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware

logger = logging.getLogger(__name__)


class RequestLoggerMiddleware(BaseHTTPMiddleware):
    """
    Middleware to log API requests and responses
    """
    
    def __init__(self, app, log_requests: bool = True, log_responses: bool = True):
        super().__init__(app)
        self.log_requests = log_requests
        self.log_responses = log_responses
    
    async def dispatch(self, request: Request, call_next):
        # Record start time
        start_time = time.time()
        
        # Log request if enabled
        if self.log_requests:
            await self._log_request(request, start_time)
        
        # Process request
        response = await call_next(request)
        
        # Calculate processing time
        process_time = time.time() - start_time
        
        # Add processing time header
        response.headers["X-Process-Time"] = str(process_time)
        
        # Log response if enabled
        if self.log_responses:
            await self._log_response(request, response, process_time)
        
        return response
    
    async def _log_request(self, request: Request, timestamp: float):
        """Log incoming request details"""
        try:
            # Basic request information
            log_data = {
                "timestamp": timestamp,
                "method": request.method,
                "url": str(request.url),
                "path": request.url.path,
                "query_params": dict(request.query_params),
                "client_host": request.client.host if request.client else None,
                "user_agent": request.headers.get("user-agent"),
                "content_type": request.headers.get("content-type"),
                "content_length": request.headers.get("content-length")
            }
            
            # Add specific headers of interest
            headers_to_log = ["authorization", "x-api-key", "x-forwarded-for", "x-real-ip"]
            logged_headers = {}
            for header in headers_to_log:
                if header in request.headers:
                    # Mask authorization headers for security
                    if "authorization" in header.lower():
                        logged_headers[header] = "Bearer ***"
                    elif "api-key" in header.lower():
                        logged_headers[header] = "***"
                    else:
                        logged_headers[header] = request.headers[header]
            
            if logged_headers:
                log_data["headers"] = logged_headers
            
            logger.info(f"REQUEST: {json.dumps(log_data, default=str)}")
            
        except Exception as e:
            logger.error(f"Error logging request: {str(e)}")
    
    async def _log_response(self, request: Request, response: Response, process_time: float):
        """Log response details"""
        try:
            log_data = {
                "method": request.method,
                "path": request.url.path,
                "status_code": response.status_code,
                "process_time": round(process_time, 4),
                "response_size": response.headers.get("content-length")
            }
            
            # Determine log level based on status code
            if response.status_code >= 500:
                log_level = logging.ERROR
                log_message = "RESPONSE ERROR"
            elif response.status_code >= 400:
                log_level = logging.WARNING
                log_message = "RESPONSE CLIENT ERROR"
            else:
                log_level = logging.INFO
                log_message = "RESPONSE SUCCESS"
            
            logger.log(log_level, f"{log_message}: {json.dumps(log_data, default=str)}")
            
        except Exception as e:
            logger.error(f"Error logging response: {str(e)}")


def request_logger_middleware(log_requests: bool = True, log_responses: bool = True):
    """Factory function to create request logger middleware"""
    def create_middleware(app):
        return RequestLoggerMiddleware(app, log_requests=log_requests, log_responses=log_responses)
    return create_middleware